<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>

            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input placeholder="请输入内容" v-model="querInfo.query" @input="getUserList" clearable>
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!--用户列表-->
            <el-table :data="userList" border stripe>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>

                <el-table-column label="状态">

                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
                        </el-switch>
                    </template>

                </el-table-column>

                <el-table-column label="操作" width="180px" >

                    <template slot-scope="scope">
                        <el-tooltip  effect="dark" content="修改" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        </el-tooltip>

                        <el-tooltip  effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
                        </el-tooltip>

                        <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>

                </el-table-column>
            </el-table>

            <!--分页-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="querInfo.pagenum"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="querInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>

        </el-card>

        <!--添加用户的对话框-->
        <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                width="50%" @close="addDialogClose">

            <el-form :model="addForm" :rules="addFormRules" ref="ruleFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>

                <el-form-item  label="密码" prop="password">
                    <el-input type="password" v-model="addForm.password"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>


                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
        </el-dialog>


        <el-dialog
                title="修改用户"
                :visible.sync="editDialogVisible"
                width="50%" @close="editDialogClose" >

            <el-form :model="editFrom" :rules="addFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editFrom.username" disabled></el-input>
                </el-form-item>



                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editFrom.email"></el-input>
                </el-form-item>


                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editFrom.mobile"></el-input>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "User",
        created() {
            this.getUserList()
        },

        data() {
            return {
            //    获取用户列表参数对象
                querInfo: {
                    query: '',
                    pagenum: 1,
                    pagesize: 2
                },

                userList: [],
                total: 0,

                addDialogVisible: false,
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                addFormRules: {
                    username: [ { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
                        ],

                    password: [ { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
                    ],

                    email: [ { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
                    ],

                    mobile: [ { required: true, message: '请输入手机', trigger: 'blur' },
                        { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
                    ]
                },

                editDialogVisible: false,

                editFrom: {}
            }
        },

        methods: {
            //需要第几页
            handleCurrentChange(newPage) {
                this.querInfo.pagenum = newPage;
                this.getUserList();
            },
            //一次要多少
            handleSizeChange(newSize) {
                this.querInfo.pagesize = newSize;
                this.getUserList();
            },
            getUserList() {

                var that = this;

                this.$http.get('users', {
                    params: this.querInfo
                }).then(function (e) {
                    if (e.data.meta.status !== 200) {
                        that.$message.error('获取用户列表失败')
                    } else {
                        that.userList = e.data.data.users;
                        that.total = e.data.data.total;
                    }

                })
            },

            // 监听 switch 开关状态的改变
            userStateChanged(userinfo) {

                var that = this;

                this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`).then(function (e) {
                    if (e.data.meta.status !== 200) {
                        userinfo.mg_state = !userinfo.mg_state;
                        that.$message.error("用户状态更新失败");
                    } else {
                        that.$message.success("用户状态更新成功")
                    }
                })
            },

            addDialogClose() {
                this.$refs.ruleFormRef.resetFields()
            },

            addUser() {

                var that = this;
                this.$refs.ruleFormRef.validate(valid => {
                    if (!valid) {
                        return
                    } else {
                        this.$http.post('users', this.addForm).then(function (e) {
                            if (e.data.meta.status !== 201) {
                                that.$message.error("添加失败");
                            } else {
                                that.$message.success("添加成功");
                                that.addDialogVisible = false;
                                that.getUserList();
                            }

                        })
                    }
                })
            },

            async showEditDialog(id) {
                var that = this;
                this.$http.get('users/' + id).then(function (e) {
                    if (e.data.meta.status !== 200) {
                        that.$message.error("用户查询失败")
                    } else {
                        that.editFrom = e.data.data;
                    }
                })
                this.editDialogVisible = true;
            },

            editDialogClose() {
                this.$refs.editFormRef.resetFields();
            },

            editUserInfo() {
                var that = this;
                this.$refs.editFormRef.validate(valid => {
                    if (!valid) {
                        return
                    } else {
                        this.$http.put('users/' + this.editFrom.id, {
                            email: this.editFrom.email,
                            mobile: this.editFrom.mobile
                        }).then(function (e) {
                            if (e.data.meta.status !== 200) {
                                that.$message.error("更新用户信息失败");
                            } else {
                                that.$message.success("更新用户信息成功");
                                that.editDialogVisible = false;
                                that.getUserList();
                            }

                        })
                    }
                });
            },

            removeUserById(id) {
                var that = this;
                console.log(id)
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                   that.$http.delete('users/' + id ).then(function (e) {
                       if (e.data.meta.status !== 200){
                           that.$message.error("删除用户失败")
                       }else {
                           that.$message.success("删除用户成功");
                           that.getUserList();
                       }
                   })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });

                });
            }

        }


    }
</script>

<style scoped>

    .el-table{
        margin-top: 15px;
    }

    .el-pagination{
        margin-top: 15px;
    }
</style>